package cn.tom.config.smsFilter;

import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.util.Assert;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


public class SmsCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    private static final AntPathRequestMatcher SPRING_SECURITY_LOGIN_PATH = new AntPathRequestMatcher("/sms/login");
    private static final String SPRING_SECURITY_FORM_MOBILE_KEY = "phone";
    private String mobileParameter = SPRING_SECURITY_FORM_MOBILE_KEY;
    private boolean postOnly = true;
    public SmsCodeAuthenticationFilter(){
        super(new AntPathRequestMatcher("/sms/login","POST"));
        // 短信登陆请求 需要以POST方式提交
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        if (postOnly && !request.getMethod().equals("POST")){
            throw new AuthenticationServiceException(" 请求方法为 "+ request.getMethod()+" 需要 POST请求");
        }
        String mobile = obtainMobile(request);
        if (mobile == null){
            mobile = "";
        }
        mobile = mobile.trim();
        SmsCodeAuthenticationToken authReq = new SmsCodeAuthenticationToken(mobile);
        setDetails(request,authReq);
        return this.getAuthenticationManager().authenticate(authReq);
//        String phone = request.getParameter("phone");
//        SmsCodeAuthenticationToken smsCodeAuthenticationToken
//                = new SmsCodeAuthenticationToken(phone);
//        return this.getAuthenticationManager().authenticate(smsCodeAuthenticationToken);
    }


    private String obtainMobile(HttpServletRequest request){
        return request.getParameter(mobileParameter);
    }
    protected void setDetails(HttpServletRequest request, SmsCodeAuthenticationToken authRequest){
        authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
    }

    public String getMobileParameter() {
        return mobileParameter;
    }

    public void setMobileParameter(String mobileParameter) {
        Assert.hasText(mobileParameter,"Mobile parameter must not be empty or null");
        this.mobileParameter = mobileParameter;
    }
    public void setPostOnly(boolean postOnly){
        this.postOnly = postOnly;
    }
}
